package com.example.farmeri.ui.person_data;

import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.example.farmeri.R;
import com.example.farmeri.common.MyCallback;
import com.example.farmeri.data.DataParam;
import com.example.farmeri.data.RetrofitManager;
import com.example.farmeri.data.config.ServiceConfig;
import com.example.farmeri.http.API;
import com.example.farmeri.pojo.User;
import com.example.farmeri.pojo.vo.BaseCallBack;
import com.example.farmeri.tools.OKHttpClientUtils;
import com.example.farmeri.tools.ResponseUtils;
import com.example.farmeri.tools.UploadUtil;
import com.example.farmeri.ui.base.BaseActivity;
import com.example.farmeri.ui.login.LoginActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 个人资料
 */
public class PersonDataActivity extends BaseActivity {

    @BindView(R.id.person_data_headImg)
    ImageView headImg;
    @BindView(R.id.person_data_nickName)
    TextView nickName;
    @BindView(R.id.person_data_introduce)
    TextView introduce;
    @BindView(R.id.person_data_userName)
    TextView userName;
    @BindView(R.id.person_data_credit)
    TextView credit;
//    @BindView(R.id.person_data_hasToken)
//    Switch hasToken;


    final static Integer ACTION_ALERT_INTRODUCE = 0;    //修改个人介绍
    final static Integer ACTION_CAMERA = 1;         //使用相机
    final static Integer ACTION_ALBUM = 2;         //使用相册

    private User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_data);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        init();

        getUserInfo();

        headImg.setOnClickListener(v -> alertDialog());
    }

    @Override
    protected void onStart() {
        super.onStart();
        setUserInfo(DataParam.getUserInfo());
    }

    SharedPreferences userSp;

    private void init(){
        initToolBar(R.id.person_data_toolbar, "个人资料", true, true);
        userSp = getSharedPreferences(getResources().getString(R.string.share_preference_user_info),MODE_PRIVATE);
    }


    private void setUserInfo(User user) {
        nickName.setText(user.getNick_name());
        userName.setText(user.getLogin_name());
        introduce.setText(user.getIntroduce());
        credit.setText(String.valueOf(user.getCredit()));
        Glide.with(this)
                .load(ServiceConfig.getRootPath(user.getIcon()))
                .centerCrop()
                .into(headImg);
    }

    private void getUserData(){
        String id = userSp.getString(getResources().getString(R.string.user_info_key_id),"");
        if (id==null||id.equals("")){
            showToast(this,"用户不能为空");
            return;
        }

        OkHttpClient client = OKHttpClientUtils.getInstance();
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();
        Request request = new Request.Builder()
                .url(ServiceConfig.updateNickName())
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new BaseCallBack(handler,0x11));

    }

    private void getUserInfo() {
        String id = DataParam.getUserInfo().getId();
        Map<String,String> map = new HashMap<String,String>();
        map.put("id",id);
        OKHttpClientUtils.userPost(ServiceConfig.viewUser(),OKHttpClientUtils.TYPE_FORM,map,new MyCallback());
    }


    final Integer WHAT_UPDATE_NICKNAME = 0x100;

    final Integer CODE_NICK_NAME = 0;
    final Integer CODE_INTRODUCE = 1;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == WHAT_UPDATE_NICKNAME){

            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updataUserInfo(ResponseUtils res){
        if (res.getCode()==200){
            String json = JSON.toJSONString(res.getData());
            user = JSON.parseObject(json,User.class);
            setUserInfo(user);
        }
    }


    //更新用户昵称
    public void updataNickName(View view) {
        if (user==null){
            return;
        }
        Intent intent = new Intent(this, UpdataNickNameActivity.class);
        intent.putExtra("id",user.getId());
        intent.putExtra("nickName",user.getNick_name());
        startActivityForResult(intent,CODE_NICK_NAME);
    }

    //更新自我介绍
    public void updataIntroduce(View view) {
        if (user==null){
            return;
        }
        Intent intent = new Intent(this, UpdataIntroduceActivity.class);
        intent.putExtra("id",user.getId());
        intent.putExtra("remarks",user.getIntroduce());
        startActivityForResult(intent,CODE_INTRODUCE);
    }


    /**
     * 弹出选择框
     */
    private void alertDialog() {
        if (false){
            useCamera();
        }else {
            selectImage();
        }
    }

    /**
     * 使用相机
     */
    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,ACTION_CAMERA);
    }

    /**
     * 使用相册
     */
    private void selectImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,ACTION_ALBUM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ACTION_ALERT_INTRODUCE) {
                introduce.setText(data.getExtras().get("introduce").toString());
            }
            else if(requestCode == ACTION_CAMERA){
                Bundle extras = data.getExtras();
                Log.d("Image","data:" + data);
                Bitmap b = (Bitmap) extras.get("data");
                headImg.setImageBitmap(b);
            }
            else if (requestCode == ACTION_ALBUM) {
                Uri uri = data.getData();
                Log.d("Image", "data:" + data);
                uploadHeadImg(uri);
                //ContentResolver cr = this.getContentResolver();
                //Cursor c = cr.query(uri,null,null,null,null);
                //c.moveToFirst();
            }
        }

    }

    private void uploadHeadImg(Uri uri) {
        String imagePath="";
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        File file = new File(imagePath);
        RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("id", DataParam.getUserInfo().getId())
                .addFormDataPart("icon",file.getName(),image)
                .build();
        RetrofitManager.getManager().getRetrofit()
                .create(API.class)
                .uploadIcon(requestBody)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseUtils>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseUtils responseUtils) {
                        if (responseUtils.getCode() == 200){
                            DataParam.getUserInfo().setIcon((String) responseUtils.getData());
                            Glide.with(PersonDataActivity.this)
                                    .load(ServiceConfig.getRootPath(DataParam.getUserInfo().getIcon()))
                                    .into(headImg);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        showToast("头像更新失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        if (DataParam.getUserInfo().getCredit()<=0){
            showToast("用户信誉值过低，已被锁定");
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
}
